package com.zt.bus.line.service;

import com.zt.bus.assistant.inter.LineStopMapper;
import com.zt.bus.assistant.model.LineStop;
import com.zt.bus.constant.BusConstant;
import com.zt.bus.line.inter.LineMapper;
import com.zt.bus.line.model.Line;
import com.zt.bus.line.model.LinePlan;
import com.zt.servlet.ReqBean;
import com.zt.system.model.BusinessException;
import com.zt.system.model.SqlBuilder;
import com.zt.system.service.BaseService;
import com.zt.util.StringUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LineService extends BaseService {

    @Autowired
    private LineMapper lineMapper;

    @Autowired
    private LineStopMapper lineStopMapper;
    @Autowired
    private LinePlanService linePlanService;

    /**
     * 查询
     * 
     * @param reqBean
     * @return
     */
    public JSONObject getTable(ReqBean reqBean) {
        SqlBuilder sqlBuilder = new SqlBuilder("select * from DZ_LINE where C_LINE_STATUS = ? ",
                BusConstant.LineStatus.ENABLE).addWhereLike2("LINE_NO", reqBean.getInfo("lineNo"))
                .addWhereLike2("LINE_NAME", reqBean.getInfo("lineName"))
                .addWhere("C_LINE_TYPE", reqBean.getInfo("lineType"))
                .addWhere("C_LINE_STATUS", reqBean.getInfo("lineStatus")).orderBy(" order by CATALOG, LINE_NAME");
        JSONObject jsonObject = queryTable(sqlBuilder, reqBean.getPageSize(), reqBean.getPageIndex());
        JSONArray array = jsonObject.getJSONArray("rows");
        for (int i = 0; i < array.size(); i++) {
            JSONObject j = array.getJSONObject(i);
            JSONArray planArray = new JSONArray();
            List<LinePlan> plans = linePlanService.getByLineId(j.getString("lineId"));
            for (LinePlan plan : plans) {
                planArray.add(plan.toJSONObject());
            }
            j.put("plans", planArray);
        }

        return jsonObject;
    }

    /**
     * 查找分组的线路，按照线路分组进行分组
     * 
     * @param lineType
     *            普通、职工专线
     * @param planStatus
     * @return
     */
    @Cacheable(value = BusConstant.Cache.LINE, key = "'catalog_' + #lineType + '_' + #planStatus")
    public JSONArray getCatalogLines(String lineType, String planStatus) {
        if (!BusConstant.LineType.CUSTOME_BUS.equals(lineType) && !BusConstant.LineType.EMPLOYEE_BUS.equals(lineType)) {
            throw new BusinessException("线路类型不存在");
        }
        JSONArray array = new JSONArray();
        Map<String, JSONObject> map = new HashMap<>();
        List<Line> list = lineMapper.selectEnableByType(lineType);
        for (Line line : list) {
            JSONArray planArray = new JSONArray();
            List<LinePlan> plans = linePlanService.getByLineId(line.getLineId());
            for (LinePlan plan : plans) {
                if (!plan.getPlanStatus().equals(planStatus)) {
                    continue;
                }
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("planId", plan.getPlanId());
                jsonObject.put("departTime", plan.getDepartTime());
                jsonObject.put("seating", plan.getSeating());
                jsonObject.put("planStatus", plan.getPlanStatus());
                planArray.add(jsonObject);
            }
            JSONObject lineObject = line.toJSONObject();
            lineObject.put("plans", planArray);

            if (planArray.size() > 0) {
                if (!map.containsKey(line.getCatalog())) {
                    JSONObject catalogJson = new JSONObject();
                    catalogJson.put("catalog", line.getCatalog());
                    catalogJson.put("lines", new JSONArray());
                    array.add(catalogJson);
                    map.put(line.getCatalog(), array.getJSONObject(array.size() - 1));
                }
                map.get(line.getCatalog()).getJSONArray("lines").add(lineObject);
            }
        }
        return array;
    }

    public JSONObject getLineDetail(String lineId, String planStatus) {
        JSONObject result = null;
        Line line = lineMapper.selectByPrimaryKey(lineId);
        if (line != null) {
            result = line.toJSONObject();
            JSONArray planArray = new JSONArray();
            List<LinePlan> plans = linePlanService.getByLineId(line.getLineId());
            for (LinePlan plan : plans) {
                if (!plan.getPlanStatus().equals(planStatus)) {
                    continue;
                }
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("planId", plan.getPlanId());
                jsonObject.put("departTime", plan.getDepartTime());
                jsonObject.put("seating", plan.getSeating());
                jsonObject.put("planStatus", plan.getPlanStatus());
                planArray.add(jsonObject);
            }
            result.put("plans", planArray);
        }
        return result;
    }

    /**
     * 查询分组信息
     * 
     * @return
     */
    public JSONArray getCatalogs(ReqBean reqBean) {
        SqlBuilder sqlBuilder = new SqlBuilder("select DISTINCT CATALOG from DZ_LINE WHERE 1 = 1 ").addWhereLike(
                "CATALOG", reqBean.getInfo("catalog")).orderBy(" ORDER BY CATALOG");
        return query(sqlBuilder);
    }

    /**
     * 通过id查询
     * 
     * @param lineId
     * @return
     */
    @Cacheable(value = BusConstant.Cache.LINE, key = "'line_' + #lineId")
    public Line getById(String lineId) {
        return lineMapper.selectByPrimaryKey(lineId);
    }

    /**
     * 新增
     * 
     * @param line
     */
    public void add(Line line) {
        line.setLineId(intIncrementId("DZ_LINE", "LINE_ID"));// 手动设置Id

        line.setLineStatus(BusConstant.LineStatus.ENABLE);
        line.setMakeTime(new Date());
        line.setModifyTime(line.getMakeTime());
        lineMapper.insert(line);
    }

    /**
     * 修改
     * 
     * @param line
     */
    @CacheEvict(value = BusConstant.Cache.LINE, allEntries = true)
    public void update(Line line) {
        String lineId = line.getLineId();
        if (StringUtil.isEmpty(lineId)) {
            throw new BusinessException("获取主键失败");
        }
        line.setLineType(null);// 这里置空，数据库不保存，不允许修改类型
        line.setModifyTime(new Date());
        lineMapper.updateByPrimaryKeySelective(line);
    }

    /**
     * 删除
     * 
     * @param lineId
     */
    @CacheEvict(value = BusConstant.Cache.LINE, allEntries = true)
    public void delete(String lineId) {
        if (StringUtil.isEmpty(lineId)) {
            throw new BusinessException("获取主键失败");
        }
        // 不做物理删除
        Line line = lineMapper.selectByPrimaryKey(lineId);
        line.setLineStatus(BusConstant.LineStatus.DISABLE); // 设置为删除状态
        line.setModifyTime(new Date());
        lineMapper.updateByPrimaryKeySelective(line);
    }

    /**
     * 获取站点
     * 
     * @param stopId
     * @return
     */
    @Cacheable(value = BusConstant.Cache.LINE, key = "'stop_' + #stopId")
    public LineStop getStop(String stopId) {
        return lineStopMapper.selectByPrimaryKey(stopId);
    }

    /**
     * 获取线路站点
     * 
     * @param lineId
     * @return
     */
    @Cacheable(value = BusConstant.Cache.LINE, key = "#lineId + '_stops'")
    public JSONArray getStops(String lineId) {
        if (StringUtils.isBlank(lineId)) {
            throw new BusinessException("获取主键失败");
        }
        String sql = "SELECT STOP_ID, STOP_NAME, C_STOP_TYPE, JINGDU, WEIDU FROM DZ_LINE_STOP a WHERE a.LINE_ID = ? and a.C_STOP_STATUS <> ? ORDER BY a.STOP_ORDER ASC";
        return query(sql, lineId, BusConstant.StopStatus.DISABLE);
    }

    /**
     * 更新线路走向
     * 
     * @param lineId
     * @param stops
     */
    @CacheEvict(value = BusConstant.Cache.LINE, allEntries = true)
    public void updateStops(String lineId, List<LineStop> stops) {
        if (stops != null && stops.size() > 0) {
            // 删除该线路的所有站点
            lineStopMapper.deleteByLineId(lineId);
            for (int i = 0; i < stops.size(); i++) {
                LineStop lineStop = stops.get(i);
                lineStop.setStopId(intIncrementId("DZ_LINE_STOP", "STOP_ID"));
                lineStop.setLineId(lineId);
                lineStop.setStopStatus(BusConstant.StopStatus.ENABLE);
                lineStop.setStopOrder(i + 1);
                lineStopMapper.insert(lineStop);
            }
        }
    }

}
